#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2020-06-05

@author: zhuyu
"""
import os
import time
import subprocess
# import commands


LOG_NAME = ''
WINDOWS = 'com.alipay.iot.xpaas/com.alipay.iot.xpaas.ui.CustomH5Activity$Portal0'
MEM_DIRS = r'D:\python\Scripts\project\PY27TEST\report' #地址

# 大屏版本
GOLF_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.master:monitor',
        'com.alipay.iot.master:worker',
        'com.alipay.mapp.content.service',
        'com.alipay.iot.settings',
        # 'zoloz.phone.android.alipay.com.dragonfly',
        # 'com.alipay.zoloz.smile',
        'com.alipay.iot.xpaas',
        'com.alipay.mapp.content.service',
        'com.alipay.mapp.content.display',
        # 'com.alipay.iot.profile',
        'com.alipay.iot.merchantplugin',
        'com.alipay.iot.miniapp.shell'
]

# 智能货柜
HUOGUI_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.master:monitor',
        'com.alipay.iot.master:worker',
        'com.alipay.iot.launcher',
        'com.alipay.vendingmachine',
        'com.alipay.takengo',
]


RUN_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.connect',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.settings',
        'com.alipay.iot.xpaas',
        'com.alipay.iot.profile',
        'com.alipay.iot.merchantplugin',
]


def gettime():
    time.localtime(time.time())
    timestamp = time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))
    return timestamp


def gettimestr():
    time.localtime(time.time())
    timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    return timestamp


def kill_adb_server():
    os.popen("adb kill-server").readlines()


def kill_app(pid):
    os.popen("adb shell kill -9 {}".format(pid))
    time.sleep(4)


def start_app():
    appinfo = []
    lines = os.popen("adb shell ps |grep alipay").readlines()
    for line in lines:
        appinfo.append(line.split(' ')[-1].strip('\n'))
    return appinfo


def get_app_info():
    appinfo = {}
    lines = os.popen("adb shell ps |grep alipay ").readlines()
    for line in lines:
        pro_info = line.split(' ')
        while '' in pro_info:
            pro_info.remove('')
        app_pid = pro_info[1]
        app_name = pro_info[-1].strip('\n')
        appinfo[app_pid] = app_name
    return appinfo


def screentshot(logname):
    pic_name = '{}.jpg'.format(logname)
    pic_path = mkdir(logname)
    os.popen('adb shell /system/bin/screencap -p /sdcard/' + pic_name)
    time.sleep(1)
    pull_cmd = 'adb pull /sdcard/' + pic_name + ' {}'.format(pic_path)
    os.popen(pull_cmd)


def get_logcat(logname):
    dirpath = mkdir(logname)
    subprocess.Popen("adb logcat > {}/logcat.txt".format(dirpath), shell=True)
    time.sleep(2)
    os.popen("adb shell dumpsys meminfo >> {}/memInfo.txt".format(dirpath))
    os.popen("adb shell cat /proc/meminfo >> {}/procmemInfo.txt".format(dirpath))
    time.sleep(2)
    os.popen("adb shell top -b -n1 >> {}/cpuInfo.txt".format(dirpath))


def mkdir(logname):
    dirs = "/Users/Administrator/PYDATA/{}".format(logname)
    if not os.path.exists(dirs):
        os.makedirs(dirs)
    return dirs


def get_sysinfo(logname):
    # 实时获取相关信息
    dirpath = mkdir(logname +'/sysinfo')
    subprocess.Popen("adb logcat > {}/logcat.txt".format(dirpath), shell=True)
    time.sleep(2)
    os.popen("adb shell dumpsys meminfo >> {}/memInfo.txt".format(dirpath))
    os.popen("adb shell cat /proc/meminfo >> {}/procmemInfo.txt".format(dirpath))
    time.sleep(2)
    os.popen("adb shell top -b -n1 >> {}/cpuInfo.txt".format(dirpath))
    # subprocess.Popen("adb bugreport  >{}/bugreport.txt".format(dirpath), shell=True)
    time.sleep(1)
    subprocess.Popen("adb shell dmesg -T  > {}/dmesg.txt".format(dirpath), shell=True)
    time.sleep(1)


def pull_sysinfo(logname):
    dirpath = mkdir(logname)
    subprocess.Popen("adb root", shell=True)
    time.sleep(1)
    os.popen("adb pull /data/system/dropbox {}/dropbox".format(dirpath))
    os.popen("adb pull /data/anr {}/anr".format(dirpath))
    os.popen("adb pull /data/tombstones {}/tombstones".format(dirpath))
    # subprocess.Popen("adb pull /data/aee_exp {}/data_aee".format(dirpath), shell=True)
    # subprocess.Popen("adb pull /data/vendor/mtklog/aee_exp {}/mtk_aee".format(dirpath), shell=True)


def checkActivity(winname):
    lines = os.popen('adb shell dumpsys window | grep mCurrentFocu').readlines()
    ret_list = lines[0].split(' ')
    while '' in ret_list:
        ret_list.remove('')
    if winname == ret_list[-1][:-2]:
        return True
    else:
        print('check start golf fail: ' + ret_list[-1][:-2])
        return False


def get_app_pid(appname):
    lines = os.popen("adb shell ps |grep {} ".format(appname)).readlines()
    if len(lines) == 0:
        print('get app pid fail {}'.format(appname))
        return
    for line in lines:
        pro_info = line.split(' ')
        while '' in pro_info:
            pro_info.remove('')
        app_pid = pro_info[1]
        appname_temp = pro_info[-1].strip('\n')
        if appname == appname_temp:
            return app_pid


def kill_antapp_test():
    os.popen("adb root")
    time.sleep(3)
    for appname in RUN_APP_LIST:
        pid1 = get_app_pid(appname)
        if pid1 is not None:
            kill_app(pid1)
        else:
            continue
        pid2 = get_app_pid(appname)
        if pid2 is not None and pid1 != pid2:
            print('test app success {} pid is {}->{}'.format(appname, pid1, pid2))


def checkconndevices():
    nodevices = 'List of devices attached'
    lines = subprocess.getstatusoutput('adb devices')[-1].split('\n')
    while '' in lines:
        lines.remove('')
    return False if nodevices == lines[-1] else True


def inputkey(key):
    subprocess.Popen("adb shell input keyevent {}".format(key), shell=True)
    time.sleep(20)


def log(info, name):
    fpath = mkdir('golfLog')
    fo = open('{}/{}.txt'.format(fpath, name), 'a')
    try:
        fo.write(gettime() + ':' + info + '\n')
    finally:
        fo.close()


def getpackagename(pid):
    outinfo = subprocess.getoutput('adb shell ps -ef| grep {}'.format(pid))
    return outinfo.split(' ')[-1]


if __name__ == "__main__":
    # get_app_pid('qq')
    # tt = commands.getstatusoutput('adb shell ps -ef |grep alipay')[1].split('\n')
    # print checkActivity(WINDOWS)
    print(os.popen("adb shell top -m 20 -n 1 -s 9").readlines()[5].split(" "))